package com.laikan.reader.apirequester;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.CommentBean;
import com.laikan.reader.core.bean.ReplyBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.socks.library.KLog;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by anrun on 9/23/16.
 */
public class CommentDetailRequester {
    public static void getReplayList(int mCurrentPage, String replyId, final TouchSwipeRefreshLayout refresher) {
        Map<String, String> map = new HashMap<>();
        map.put("page", mCurrentPage + "");
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("FocusCommentDetailActivity : " + httpResponse.responseContent);
                BaseDataBean<CommentBean<ReplyBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<CommentBean<ReplyBean>>>(){}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);

                    if (result != null) {
                        if(result.getError_no().equals("102")){   //是封禁用户
                            loadDataFailed("userClose");
                        }else{
                            if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                                loadDataFailed("datafailed");
                            }else {
                                LaiKanEvent event = LaiKanEvent.getInstance();
                                event.setEventID(LaiKanEvent.EVENT_ID_GET_REPLY_LIST);
                                event.setElves(result);
                                LaikanApplication.postEvent(event);
                            }
                        }
                    }else {
                        loadDataFailed("datafailed");
                    }
                }catch (Exception e) {
                    // 数据解析失败
                    loadDataFailed("datafailed");
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                loadDataFailed("netfailed");
                KLog.e("网络不给力，请重试。10");
            }

            @Override
            public void onFinish() {
                refresher.setRefreshing(false);
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_get_commentdetail + replyId);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_get_commentdetail + replyId, map, null, null, requestListener);
    }

    private static void loadDataFailed(String action){
        LaiKanEvent event = LaiKanEvent.getInstance();
        event.setEventID(LaiKanEvent.EVENT_ID_COMMENT_NOTIC);
        event.setEventAction(action);
        LaikanApplication.postEvent(event);
    }
    /**
     * 获取回应接口数据
     */
    public static void loadMoreReplayDate(int mCurrentPage, String replyId, final TouchSwipeRefreshLayout refresher) {
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<BaseListDataBean<ReplyBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<ReplyBean>>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);

                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            LaiKanEvent event = LaiKanEvent.getInstance();
                            event.setEventID(LaiKanEvent.EVENT_ID_GET_MORE_REPLY);
                            event.setElves(result);
                            LaikanApplication.postEvent(event);
                        }
//                        ToastMgr.showShortToast(R.string.fw_data_loading_done);
                    }else {
                        showNotice(1);
                    }
                }catch (Exception e) {
                    showNotice(1);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                showNotice(2);
                KLog.e("网络不给力，请重试。11");
            }

            @Override
            public void onFinish() {
                refresher.setLoading(false);
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_get_add_commentdetail + replyId + "/list?page=" + mCurrentPage);
//        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpGetRequest(APIProtocol.laikan_get_add_commentdetail + replyId + "/list?page=" + mCurrentPage, null, null, requestListener);
    }

    /**
     * @param type 为 1 数据加载失败
     * @param type 为 2 网络异常
     */
    private static String showContent;
    private static void showNotice(int type){
        if(type == 1){
            showContent = BasicApplication.getInstance().getString(R.string.laikan_data_load_failed);
        }else if(type == 2){
            showContent = BasicApplication.getInstance().getString(R.string.laikan_network_anomaly);
        }
        LaiKanEvent event = LaiKanEvent.getInstance();
        event.setEventID(LaiKanEvent.EVENT_ID_SHOW_NOTICE);
        event.setEventAction(showContent);
        LaikanApplication.postEvent(event);
    }
    /**
     * 发送评论回复
     * @param comment
     * @param replyId
     * @param mloadingDialog
     */
    public static void sendReply(String comment, String replyId, final LoadingDialog mloadingDialog) {
        if (comment.length() == 0) {
            ToastMgr.showShortToast(R.string.laikan_empty_content_toast);
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("content", comment);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                mloadingDialog.show();
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (Constants.RESULT_OK.equals(result)) {
                        ToastMgr.showShortToast(R.string.comment_success);
                        LaiKanEvent event = LaiKanEvent.getInstance();
                        event.setEventID(LaiKanEvent.EVENT_ID_SEND_REPLY);
                        LaikanApplication.postEvent(event);
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }
                }catch (Exception e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。12");
            }

            @Override
            public void onFinish() {
                mloadingDialog.dismiss();
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_get_add_commentdetail + replyId + "/add?");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_get_add_commentdetail + replyId + "/add?", map, null, null, requestListener);
    }
}
